<template>
  <Form
    ref="fm"
    :validation-schema="rules"
    v-slot="{ errors }"
    class="xtx-form"
  >
    <!-- QQ登录成功以后显示的成功信息 -->
    <div class="user-info">
      <img :src="qqUser.photo" alt="" />
      <p>Hi，{{ qqUser.name }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <!-- 绑定QQ号到已注册的小兔鲜账号 => 目的: 绑定之后,用QQ扫码登录 (等价于用绑定的小兔鲜账号登录) -->
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="formData.mobile"
          name="mobile"
          class="input"
          :class="{ err: errors.mobile }"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div class="error" v-show="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="formData.code"
          name="code"
          class="input"
          :class="{ err: errors.code }"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="handlerCode">{{
          count === 0 ? "发送验证码" : `${count}秒后发送`
        }}</span>
      </div>
      <div class="error" v-show="errors.code">{{ errors.code }}</div>
    </div>
    <a @click="bindQQ" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { ref, reactive } from 'vue'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { message } from '@/components/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// 导入发送验证码公共方法
import { useSendCode } from '@/hooks/page'
// 获取QQ登录成功后的账号信息
const useQQ = () => {
  // 存储QQ账号信息
  const qqUser = ref({
    name: '',
    photo: ''
  })

  if (window.QC.Login.check()) {
    // 请求获取QQ登录后的账号信息
    window.QC.api('get_user_info').success((res) => {
      qqUser.value.name = res.data.nickname
      qqUser.value.photo = res.data.figureurl_1
    })
  }
  return { qqUser }
}

// 表单校验
const useValidateForm = () => {
  // 表单数据
  const formData = reactive({
    mobile: '', // 手机号
    code: '' // 验证码
  })

  // 校验规则
  const rules = {
    mobile: schema.mobile,
    code: schema.code
  }
  return { formData, rules }
}

// QQ号绑定小兔鲜账号
const useSubmit = (fm, props, formData) => {
  const store = useStore()
  const router = useRouter()
  // 点击绑定的事件回调
  const bindQQ = async () => {
    /**
     * 1- 表单整体校验
     * 2- 校验通过执行绑定 => 获取登录人信息存储 => 跳转首页
     */
    const res = await fm.value.validate()
    try {
      if (res.valid) {
        // 校验通过
        const { result } = await userQQBindLogin({
          unionId: props.unionId,
          ...formData
        })
        // 存储当前登录人信息
        await store.commit('user/setProfile', result)
        // 登录成功之后 => 合并之前本地购物车数据,到当前登录人名下
        await store.dispatch('cart/mergeCartAction')
        message({ type: 'success', text: 'QQ绑定成功' })
        router.replace('/')
      }
    } catch (error) {
      message({ type: 'error', text: 'QQ绑定失败' })
    }
  }
  return { bindQQ }
}

export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: {
    Form,
    Field
  },
  setup (props) {
    const { qqUser } = useQQ()
    const { formData, rules } = useValidateForm()
    const { handlerCode, fm, count } = useSendCode(formData, userQQBindCode)
    // 提交
    const { bindQQ } = useSubmit(fm, props, formData)
    return { qqUser, formData, rules, handlerCode, fm, count, bindQQ }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
